<?php
class Admin_product_Controller extends Template_Controller {
	
	var $mr;
	var $mlist;
	
	public $template = 'admin/index';
	
	public function __construct()
    {
        parent::__construct(); // This must be included
 
        $this->search = array('keyword' => '');
        
        $this->_get_submit();
    }

	public function __call($method, $arguments)
	{
		// Disable auto-rendering
		$this->auto_render = FALSE;
	}

	function _get_submit()
	{
		if($this->session->get('error_msg'))
		  $this->template->error_msg = $this->session->get('error_msg');
		if($this->session->get('warning_msg'))
		  $this->template->warning_msg = $this->session->get('warning_msg');
		if($this->session->get('success_msg'))
		  $this->template->success_msg = $this->session->get('success_msg');
		if($this->session->get('info_msg'))
		  $this->template->info_msg = $this->session->get('info_msg');
	}
	
	public function index()
	{
		//$this->_make_random();
		$tmp = ORM::factory('language')->find();
		$this->mr['languages_id'] = $tmp->languages_id;
		$this->mr['languages_image'] = $tmp->languages_image;
		$this->mr['sel_status'] = "";
		$this->mr['product_name'] = '';
		$this->showlist();		
	}
	
	private function _format_showlist($mlist)
	{
		for($i=0; $i<count($mlist); $i++)
		{
			$mlist[$i]['products_our_price'] = $this->format_currency($mlist[$i]['products_our_price'],$this->site['site_currency']);
		}
		return $mlist;
	}
	
	private function _make_random()
	{
		$this->db->select();
		$this->db->from('products');
		$model = $this->db->get();
		$mlist = $model->result_array(false);
		for($i=0; $i<count($mlist); $i++)
		{
			$mlist[$i]['products_weight'] = rand(1,9);
			$mlist[$i]['products_length'] = rand(1,9);
			$mlist[$i]['products_width'] = rand(1,9);
			$mlist[$i]['products_height'] = rand(1,9);
			$this->db->update('products',$mlist[$i],array('products_id' => $mlist[$i]['products_id']));
		}
	}
	
	private function _update_summary()
	{
		$this->db->select();
		$this->db->from('products_description');
		$model = $this->db->get();
		$mlist = $model->result_array(false);
		for($i=0; $i<count($mlist); $i++)
		{
			$this->db->update('products_description', array('products_summary' => $mlist[$i]['products_description']),array('products_id' => $mlist[$i]['products_id']));
		}
	}
	
	private function _update_no()
	{
		$this->db->select();
		$this->db->from('products');
		$model = $this->db->get();
		$mlist = $model->result_array(false);
		for($i=0; $i<count($mlist); $i++)
		{
			$this->db->update('products', array('products_no' => $mlist[$i]['products_serial_number']),array('products_id' => $mlist[$i]['products_id']));
		}
	}
	
	private function _update_point()
	{
		$this->db->select();
		$this->db->from('products');
		$model = $this->db->get();
		$mlist = $model->result_array(false);
		for($i=0; $i<count($mlist); $i++)
		{
			$point = rand(1,9)*10;
			$this->db->update('products', array('products_point' => $point),array('products_id' => $mlist[$i]['products_id']));
		}
	}
	
	public function showlist()
	{
		$this->template->content = new View('admin_product/list');
        
        //Assign
        if(isset($this->search['keyword']))
            $this->template->content->keyword = $this->search['keyword'];
        
        $model = new Product_Model();
        $cat = new Product();
        $this->where_sql();
		$mlist = $cat->get($model);
        
		//Pagination
    	$this->pagination = new Pagination(array(
    		'base_url'    => 'admin_product/search/',
		    'uri_segment'    => 'page',
		    'total_items'    => count($mlist),
		    'items_per_page' => $this->site['site_num_line2'],
		    'style'          => 'classic',
		));		
		$this->db->limit($this->pagination->items_per_page,$this->pagination->sql_offset);
 	
        $this->where_sql();
    	$mlist = $cat->get($model);
		$mlist = $this->_format_showlist($mlist);    	
    	$this->template->content->mlist = $mlist;
        //Language
		$model_lang = new Language_Model();	
		$this->template->content->list_language = $model_lang->get_with_active();
		$this->_get_submit();		
	}
	
    public function where_sql()
    {
        if($this->search['keyword']){
            $this->db->like('products_name',$this->search['keyword']);
        }
    }
    
	public function search()
	{
		if($this->session->get('sess_search')){			
			$this->search = $this->session->get('sess_search');	
		}
		//Keyword
        $keyword = $this->input->post('txt_keyword');
		if(isset($keyword))
			$this->search['keyword'] = $keyword;
		
		$this->session->set_flash('sess_search',$this->search);
		$this->showlist();
	}
    
    private function _list_language()
    {
        $model_lang = new Language_Model();		
		$this->template->content->list_language = $model_lang->get_with_active();
    }
    
    private function _list_category()
    {
        $model = new Category_Model();
        $cat = new Category();
		$this->template->content->list_category = $cat->get($model);
    }
    
	public function create()
	{
		$this->template->content = new View('admin_product/frm');
        //Language
		$this->_list_language();
        //Category
       	$this->_list_category();
	}
	
    private function _set_form_inventory($form)
    {
    	$record['inventory_date'] = time();
		//Int    	
    	if($form['rdo_in_out'] == 1){
    		$record['inventory_description'] = 'In';//$form['sel_input'];
    		$record['inventory_status'] = 1;
    	//Out
    	} elseif($form['rdo_in_out'] == 2){
    		$record['inventory_description'] = 'Out';
    		$record['inventory_status'] = 2;
    	//Adjust in
		} elseif($form['rdo_in_out'] == 3){
    		$record['inventory_description'] = 'Adjust in';
    		$record['inventory_status'] = 1;
    	//Adjust out
		} elseif($form['rdo_in_out'] == 4){
    		$record['inventory_description'] = 'Adjust out';  
    		$record['inventory_status'] = 2;
		}		
		$record['products_qty'] = $form['txt_qty_inventory'];		
		$record['vendors_name'] = $form['txt_vendor_name'];
		$record['inventory_remark'] = $form['txt_remark'];
		return $record;
	}
    
	private function _get_record()
	{		
		$form = array(
	    	'categories_id'   => '',
	    	'hd_id'			=> '',	        
	        'txt_sort_order'    => '',
	        'chk_delete'		=> '',
			'sel_status'   => '',
			'txt_no' => '',
			'sel_show'	=> '',
			//Price
	        'txt_msrp_price'	=> '',
			'txt_our_price'		=> '',
			'txt_sale_price'	=> '',
			'txt_wholesale'		=> '',
			'txt_msrp_date_from'	=> '',
			'txt_msrp_date_to'		=> '',
			'txt_sale_date_from'	=> '',
			'txt_sale_date_to'	=> '',
			'txt_vat'		=> '',
			//Qty
			'txt_qty'	=> '',
			'txt_mini_quantity' => '',
			//Image	
			'hd_old_image'		=> '',
			'hd_old_image2'		=> '',
			'hd_old_image3'		=> '',
			'hd_old_image4'		=> '',
			//Dimension
			'txt_weight'		=> '',
			'txt_length'		=> '',
			'txt_width'		=> '',
			'txt_height'		=> '',
			//Promotion
			'txt_point'		=> '',
		);
		$tmp = ORM::factory('language')->where('languages_status',1)->find_all();
	
		foreach ($tmp as $list)
		{
			$form['txt_name'.$list->languages_id] = '';
			$form['txt_description'.$list->languages_id] = '';
			$form['txt_summary'.$list->languages_id] = '';
		}
	 
	    $errors = $form;
	 	
	    if ($_POST)
	    {
	        $post = new Validation($_POST);
	 		
	        $post->pre_filter('trim', TRUE);
	        foreach ($tmp as $list)
			{
				$post->add_rules('txt_name'.$list->languages_id,'required');
			}
	        
	        if ($post->validate())
	        {
	        	$form = arr::overwrite($form, $post->as_array());
     			return $form;
	        } else {
	        	
	        	$form = arr::overwrite($form, $post->as_array());
	            $errors = arr::overwrite($errors,$post->errors('product_validation'));
	            $str = '';
	            foreach ($tmp as $list)
				{
					if ($errors['txt_name'.$list->languages_id])
						$str .= $errors['txt_name'.$list->languages_id].'<br>';
				}
				$this->session->set_flash('error_msg', $str);
				
				if ($form['hd_id'])
					url::redirect('admin_product/edit/'.$form['hd_id']); 
				else
					url::redirect('admin_product/create'); 
	        }
			
	    }
	}
	
    private function _get_record_inventory()
    {
    	$form = array
	    (
	    	'rdo_in_out' => '',
	    	//'sel_input' => '',
	    	//'sel_output' => '',
	        'txt_qty_inventory' => '',
	        'txt_vendor_name' => '',
	        'txt_remark' => '',
	    );
		
		$errors = $form;
		
		if($_POST)
    	{
    		$post = new Validation($_POST);
    		
			$post->pre_filter('trim', TRUE);
			$post->add_rules('rdo_in_out','required');
			$post->add_rules('txt_qty_inventory','required','numeric');
			
			$form = arr::overwrite($form, $post->as_array());
			//Product
			$form = $this->_set_form_inventory($form);
			if($post->validate())
 			{
 				return $form; 				
			} else {				
				$this->session->set_flash('frm',$form);
				$errors = arr::overwrite($errors, $post->errors('product_inventory_validation'));
				$str_error = '';
				foreach($errors as $id => $name) if($name) $str_error.='<br>'.$name;
				$this->session->set_flash('error_msg',$str_error);				
				
				$hd_id = $this->input->post('hd_id');
				if($hd_id)
					url::redirect('admin_product/edit/'.$hd_id);
				else
					url::redirect('admin_product/create');
				die();
			}
        }
    }
    
	private function _get_image($chk_delete,$hd_old_image,$name)
	{
		//============Check image old=====================	
		if($hd_old_image)
		{
			$path_filedel = './uploads/product/'.$hd_old_image;
		} 
		else	
			$path_filedel = '';
	
		if($chk_delete)
		{
			if(file_exists($path_filedel)) unlink($path_filedel);
			
			return '';
		}
		//============Upload==============================	
		// uses Kohana upload helper	
		
		/*$_FILES = Validation::factory($_FILES)
			->add_rules($name, 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[1M]');*/
			
		if ($_FILES[$name]['error']==0)
		{
			//delete file if have upload image
			if(file_exists($path_filedel)) unlink($path_filedel);
			
			// Temporary file name
			$filename = upload::save($name);
			// Resize, sharpen, and save the image
			//print_r($_FILES['txt_image']);
			//exit();
			Image::factory($filename)
				->resize(250, 250,Image::AUTO)
				->save(DOCROOT.'uploads/product/'.md5(basename($filename)).'.png');
		 	
			// Remove the temporary file
			unlink($filename);
		 
			// Redirect back to the account page
			return md5(basename($filename)).'.png';
		} else {
			if ($hd_old_image)
				return $hd_old_image;
			else
				return '';
		}
	}
	
	private function _save_product($hd_id,$record)
	{
		if(!$hd_id){
			$result = ORM::factory('product');
		} else {
			$result = ORM::factory('product',$hd_id);
		}
		$result->products_date_added = date('y-m-d h:i:s');
		$result->products_last_modified = date('y-m-d h:i:s');
		$result->master_categories_id = $record['categories_id'];
		$result->products_status = $record['sel_status'];
		$result->products_sort_order = $record['txt_sort_order'];
		$result->products_no = $record['txt_no'];
		$result->products_show = $record['sel_show'];		
		//Price
		$result->products_msrp_price = $record['txt_msrp_price'];
		$result->products_our_price = $record['txt_our_price'];
		$result->products_sale_price = $record['txt_sale_price'];
		$result->products_wholesale_price = $record['txt_wholesale'];
		$msrp_date_from=$this->format_str_date($record['txt_msrp_date_from'],'m/d/Y');
		$msrp_date_to=$this->format_str_date($record['txt_msrp_date_to'],'m/d/Y');		
		$sale_date_from=$this->format_str_date($record['txt_sale_date_from'],'m/d/Y');
		$sale_date_to=$this->format_str_date($record['txt_sale_date_to'],'m/d/Y');
		$result->products_msrp_date_from = $msrp_date_from;
		$result->products_msrp_date_to = $msrp_date_to;
		$result->products_sale_date_from = $sale_date_from;
		$result->products_sale_date_to = $sale_date_to;
		$result->products_vat = $record['txt_vat'];
		//Qty
		$result->products_qty = $record['txt_qty'];
		$result->products_mini_quantity = $record['txt_mini_quantity'];
		//Image
		if($_FILES['txt_image']['name']!="")
		$result->products_image = $this->_get_image($record['chk_delete'],$record['hd_old_image'],'txt_image');
		if($_FILES['txt_image2']['name']!="")
		$result->products_image2 = $this->_get_image($record['chk_delete'],$record['hd_old_image2'],'txt_image2');
		if($_FILES['txt_image3']['name']!="")
		$result->products_image3 = $this->_get_image($record['chk_delete'],$record['hd_old_image3'],'txt_image3');
		if($_FILES['txt_image4']['name']!="")
		$result->products_image4 = $this->_get_image($record['chk_delete'],$record['hd_old_image4'],'txt_image4');		
		//Dimension
		$result->products_weight = $record['txt_weight'];	
		$result->products_length = $record['txt_length'];
		$result->products_width = $record['txt_width'];
		$result->products_height = $record['txt_height'];
		//Promotion
		$result->products_point = $record['txt_point'];
		
		$hd_id = $result->save();
		return $hd_id;
	}
	
	private function _save_product_desc($hd_id,$record)
	{
		$tmp = ORM::factory('language')->where('languages_status',1)->find_all();
		
		foreach($tmp as $list)
		{
			$query = $this->db->query("SELECT * FROM products_description where products_id=" .$hd_id .' and languages_id ='.$list->languages_id);
 
			if($query->count()>0)
			{
				$this->db->update('products_description', 
					array('products_name' => $record['txt_name'.$list->languages_id],
						  'products_description' => $record['txt_description'.$list->languages_id],
						  'products_summary' => $record['txt_summary'.$list->languages_id]
						  ), 
					array('products_id' => $hd_id,
						  'languages_id' => $list->languages_id
						 )
					);
			} else {
				$this->db->insert('products_description',									
					array('products_id' => $hd_id,
						  'languages_id' => $list->languages_id,
						  'products_name' => $record['txt_name'.$list->languages_id],
						  'products_description' => $record['txt_description'.$list->languages_id],
						  'products_summary' => $record['txt_summary'.$list->languages_id]
						)
				);
			}
		}
	}
	
	public function save()
	{
		$hd_id = $this->input->post('hd_id');
		
		$category_relation = $this->input->post('category_relation');
		$record = $this->_get_record();
		
		if($record)
		{
			$hd_id1 =  $this->_save_product($hd_id,$record);
			
			$this->_save_product_desc($hd_id1,$record);
		}
		if(!empty($category_relation)){
			$this->db->delete('products_to_categories', array('products_id' => $hd_id));
			for($i=0;$i<count($category_relation);$i++){
				$this->db->insert('products_to_categories',		
						array('products_id' => $hd_id,
							  'categories_id' => $category_relation[$i],
						)
				);
			}
		}
		
		if(!$this->input->post('hd_id'))
			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_add'));
		else
			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));
		url::redirect('admin_product/edit/'.$hd_id1);     
	}
	
	private function _update_inventory_qty($id,$product_id)
	{
		$result = ORM::factory('inventory')->find($id)->as_array();
		$result_product = ORM::factory('product')->find($product_id)->as_array();
		//Inventory
    	$result['products_id'] = $product_id;
    	//Name
    	$list_lang = ORM::factory('language')->where('languages_status',1)->find_all();		
		foreach($list_lang as $list)
		{
			$this->db->select();
			$this->db->from('products_description');
			$this->db->where('products_id',$product_id);
			$this->db->where('languages_id',$list->languages_id);			
			$query = $this->db->get();
			$list = $query->result_array(false);
			$result['products_name'] = $list[0]['products_name'];
		}
		$result['products_no'] = $result_product['products_no'];
		$result['products_price'] = $result_product['products_our_price'];
		$result['products_weight'] = $result_product['products_weight'];
		$this->db->update('inventory', $result, array('inventory_id' => $id));
		
		//Product
		if($result['inventory_status'] == 1 || $result['inventory_status'] == 3)
			$result_product['products_qty'] += $result['products_qty'];
		elseif($result['inventory_status'] == 2 || $result['inventory_status'] == 4)
			$result_product['products_qty'] -= $result['products_qty'];
		$this->db->update('products', $result_product, array('products_id' => $product_id));
	}
	
	public function save_inventory()
	{
		$hd_id = $this->input->post('hd_id');	
    	
    	$record = $this->_get_record_inventory();		
		
		if($record)
		{
			$query = $this->db->insert('inventory', $record);
			$id = $query->insert_id();	
			//Update			
	        $this->_update_inventory_qty($id,$hd_id);
			if(!$this->input->post('hd_id'))
				$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_add'));
			else
				$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));
		}
		url::redirect('admin_product/edit/'.$hd_id);
		die(); 
	}
	
	public function saveall()
	{
		$arr_id = $this->input->post('chk_id');
		$status = array();
		if(is_array($arr_id))
		{			
			$sel_action = $this->input->post('sel_action');		
			if($sel_action == 'delete')
			{
				for($i=0;$i<count($arr_id);$i++)
				{
					$this->db->delete('products_description', array('products_id' => $arr_id[$i]));
	 				$status = $this->db->delete('products', array('products_id' => $arr_id[$i]));
				}
			} elseif($sel_action == 'block') {
				for($i=0;$i<count($arr_id);$i++)
				{
					$status = $this->db->update('products', array('products_status' => 0), array('products_id' => $arr_id[$i]));
				}
			} elseif($sel_action == 'active') {
				for($i=0;$i<count($arr_id);$i++)
				{
					$status = $this->db->update('products', array('products_status' => 1), array('products_id' => $arr_id[$i]));
				}
			}
		} else {
			$this->session->set_flash('warning_msg',Kohana::lang('errormsg_lang.msg_data_error'));
		}		
		if (count($status)>0)
			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));
		url::redirect('admin_product');
	}
	
	public function edit($id)
	{
		$this->template->content = new View('admin_product/frm');
		//Language
        $this->_list_language();
        //Category
        $this->_list_category();
        //Product
		$model = new Product_Model();
        $cat = new Product();	
		$list = $cat->get($model,$id);
		$mr = $list[0]['languages'];
		$this->template->content->mr = $mr;
		$this->_get_submit();			
	}
	
	public function delete($id)
	{
		$this->db->delete('products_description',array('products_id' => $id));
 		$status = $this->db->delete('products',array('products_id' => $id));
		if(count($status)>0)
		{
			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_del'));
		}
		url::redirect('admin_product'); 
		die();    
	}
	
	public function delete_image($id,$image)
	{
		$this->db->select();
		$this->db->from('products');
		$this->db->where('products_id',$id);
		$model = $this->db->get();
		$arrProduct = $model->result_array(false);
		$image = ($image==1)?'':$image;
		$imageName= $arrProduct[0]['products_image'.$image];
		if($imageName)
		{
			$path_filedel = './uploads/product/'.$imageName;
		} 
			
		if($path_filedel)
		{
			if(file_exists($path_filedel)) unlink($path_filedel);
						
		}
		
		$result = ORM::factory('product',$id);
		if($image=='')
		$result->products_image = '';
		if($image==2)
		$result->products_image2 = '';
		if($image==3)
		$result->products_image3 = '';
		if($image==4)
		$result->products_image4 = '';
		
		$result->save();
		url::redirect('admin_product/edit/'.$id); 
	}
	
	public function setstatus($id,$s)
	{
		$status = $this->db->update('products',array('products_status' => $s),array('products_id' => $id));
		if(count($status)>0)
		{
			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_status_change'));
		}
		url::redirect('admin_product');
		die();
	}
	
	public function change_language($id)
	{
		if(request::is_ajax())
		{
			$this->auto_render=false; 
			$result=ORM::factory('language')->find($id);
			
	        echo $result->image; 
		} else {
			$this->template->content='nothing yet';
		}
	}
	
	public function import()
	{
		$this->template->content = new View('admin_product/frm_import');
		$this->_get_submit();		
	}
	
	public function _read_excel($filename)
	{
		$data = new Excel();
        $data->setOutputEncoding('CP1251');
		$data->read($filename);    
		//error_reporting(E_ALL ^ E_NOTICE);
		for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
			if(isset($data->sheets[0]['cells'][$i][1])){
				$result = ORM::factory('product');
				$result->products_date_added = date('y-m-d h:i:s');
				$result->products_last_modified = date('y-m-d h:i:s');			
				$result->products_no = $data->sheets[0]['cells'][$i][1];
				if(isset($data->sheets[0]['cells'][$i][4])){
					$qty = trim($data->sheets[0]['cells'][$i][4]);
					$result->products_qty = $qty;
				}				
				if(isset($data->sheets[0]['cells'][$i][5])){
					$price = trim($data->sheets[0]['cells'][$i][5]);
					$result->products_msrp_price = $price;
					$result->products_our_price = $price;
					$result->products_sale_price = $price;
				}
				$result->products_status = 1;
				$id = $result->save();
				$model_lang = new Language_Model();			
				$list_lang = $model_lang->get_with_active();
				for($j=0; $j<count($list_lang); $j++)
				{
					$this->db->insert('products_description',									
					array('products_id' => $id,
						  'languages_id' => $list_lang[$j]['languages_id'],
						  'products_name' => $data->sheets[0]['cells'][$i][2],
						  'products_description' => $data->sheets[0]['cells'][$i][3]
						)
					);
				}				
			}
		}
	}
	
	public function sm_import()
	{
		$this->template->content = new View('admin_product/frm_import');
		
		$_FILES = Validation::factory($_FILES)
			->add_rules('txt_import', 'upload::valid', 'upload::type[xls]', 'upload::size[10M]');
			
		if($_FILES['txt_import']['error']==0)
		{
			Kohana::config_set('upload.directory', DOCROOT.'uploads/import');
			$filename = upload::save('txt_import');	
			if($filename)
				$this->_read_excel($filename);
			
			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));		
		} else {
			$this->session->set_flash('warning_msg',Kohana::lang('errormsg_lang.msg_data_error'));
		}
		url::redirect('admin_product/import');
	}
}